const router = require('koa-router')()
const axios = require('axios');
const WXBizDataCrypt = require('../utils/WXBizDataCrypt')
const {AppInfo,TokenConf} =  require('../conf/config')
const {login,registered,update,getUserInfo,setUserInfo} = require('../controller/login')
const {SuccessModel,ErrorModel} = require('../model/resModel.js')
const jwt = require('jsonwebtoken')


router.prefix('/user')

router.get('/login', async (ctx, next) => {
    const {code} = ctx.query
    const url ='https://api.weixin.qq.com/sns/jscode2session'
    const res= await axios.get(url,{params:{
      appid:AppInfo.appid,
      secret:AppInfo.secret,
      js_code:code,
      grant_type:"authorization_code"
    }})
    const {openid,session_key}=res.data
    const userInfo = await login(openid)
    if(userInfo){
      const updateBool = await update(openid,session_key)
      const token = jwt.sign({id:userInfo.id},TokenConf.secret,{
        expiresIn:TokenConf.time
      })
      if(updateBool){
        ctx.body = new SuccessModel({
          userInfo,
          token
        })
        return
      }
      
    }
    const newUser = await registered(openid,session_key)
    if(newUser){
      const token = jwt.sign({id:newUser.id},TokenConf.secret,{
        expiresIn:TokenConf.time
      })
      ctx.body = new SuccessModel({
        token
      })
      return
    }
    ctx.body = new ErrorModel('登陆失败')

  })
  

router.post('/authorization',async (ctx, next) => {
    const body=ctx.request.body
    let id=ctx.state['user'].id
    const userInfo =await getUserInfo(id)
    var pc = new WXBizDataCrypt(AppInfo.appid, userInfo.session_key)
    var data = pc.decryptData(body.encryptedData , body.iv)
    const setDataBool = await setUserInfo(id,data)
    if(setDataBool){
      ctx.body=new SuccessModel({
        ...data
      })
      return
    }
    ctx.body = new ErrorModel('授权失败')
  })

  router.get('/haha',async (ctx, next) => {
    
    ctx.body = new ErrorModel('lala')
  })
  
  module.exports = router
  